<!DOCTYPE HTML>
<html>
<head>
    <title>Flask-SocketIO Test</title>
    <script src="//code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            var socket = io({
                'reconnectionDelay': 500,
                'reconnectionDelayMax': 1000,
                'timeout': 3000,
                transports: ['websocket']
            });
            // Event handler for new connections.
            socket.on('connect', function() {
                console.log('Socketio connected '+ new Date().toISOString());
            });
            socket.on('disconnect', function() {
                console.log('Socketio disconnected  '+ new Date().toISOString());
                $('#podname').text('')
            });
            socket.on('connect_error', function() {
                console.log('connect_error  '+ new Date().toISOString());
            });
            socket.on('connect_timeout', function() {
                console.log('connect_timeout  '+ new Date().toISOString());
            });
            socket.on('pod_id', function(msg) {
                console.log('Connected to pod: '+msg);
                $('#podname').text(msg)
            });
            // Event handler for server sent data.
            // Splits the received transcription into its steady/pending/unstable
            // parts, and displays on-page.
            var re = new RegExp('^\\[.+\\]');
            socket.on('transcript', function(msg, cb) {
                var elems = msg.split("|");
                if (elems.length > 0) {
                    // if this is a 'control' message, add a line break
                    if (re.test(elems[0])) {
                        $('#steady').append('<br>');
                    }
                    $('#steady').append(elems[0]+' ');
                }
                if (elems.length > 1) {
                    $('#pending').text(elems[1]);
                    if (elems.length > 2) {
                        $('#unstable').text(elems[2]);
                    }
                }
                // clear if not present
                if (elems.length < 3) {
                    $('#unstable').text('');
                    if (elems.length < 2) {
                        $('#pending').text('');
                    }
                }
            });
        });
    </script>
</head>
<body>
<h1>Live Transcription Demo</h1>
<p><b>Connected to:  </b><span id="podname"></span></p>
<h3>Received:</h3>
<div id="steady" style="width:500px"></div>
<br>
<div id="pending" style="color:Gray"></div>
<div id="unstable" style="color:Silver"></div>
</body>
</html>
